

"""
-------------------------------------------------
        同目录调用方法
        # -*- coding: utf-8 -*-
    from vip_request_ini import vip_request

   File Name：     vip_request
   Description :   used for init request needs parms
   用于提供给request方便维护的header 和cookies
   header 可以有随机ua
   Author :        shenhuawade
   date：          2019/7/23
-------------------------------------------------
-------------------------------------------------
"""
import json
import os
import random

import requests
import time
from fake_useragent import UserAgent # 获取随机useragent
import logging
from logging.handlers import RotatingFileHandler

ua = UserAgent().random
class vip_request:


    #构造header
    def get_header(self):
        # header 伪装浏览器设置（下面的二选一，看哪个合适）
        headers = {
            # 'User-Agent': UserAgent(verify_ssl=False).random,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Cookie": "ABTEST=2|1561358499|v1; IPLOC=CN1100; SUID=1A4FC17C4631990A000000005D1070A3; SUV=00CDEE0D7CC14F1A5D1070A35DFF7862; SUID=1A4FC17C2113940A000000005D1070A3; weixinIndexVisited=1; pgv_pvi=2997798912; ld=tZllllllll2N9tTHlllllV1S8k7lllllKGV5pklllltlllllpylll5@@@@@@@@@@; LSTMV=682%2C416; LCLKINT=8742; SNUID=F7A22C91EDE961A343DEFB22EDD4F97E; sct=14; JSESSIONID=aaaoA1hhCs7Mf8ji7bsTw",
            "Host": "weixin.sogou.com",
            "Pragma": "no-cache",
            "Referer": "https://weixin.sogou.com/weixin?usip=&query=%E9%98%BF%E5%B0%94%E6%B3%95%E7%8B%97&ft=&tsn=1&et=&interation=&type=2&wxid=&page=2&ie=utf8",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
        }
        # print(headers)
        return headers





    #构造cookie
    def getcookie(self):
        #初始化cookie，把需要写入的cookie加入到里边
        # cookie ='SNUID=D7729710D0CA418AD4E396C0D05B88DA; IPLOC=CN4103; SUID=07BD58DF2E08990A000000005D35BAE7; SUV=00DB16B6DF58BD075D35BAE8C781D995; ld=8lllllllll2N2brXlllllV1T4IllllllTCAdxZllll9lllllVZlll5@@@@@@@@@@; LSTMV=239%2C71; LCLKINT=1380; ABTEST=0|1563893394|v1; JSESSIONID=aaaT3iFA5HKhn-DXeV7Qw; sct=2'
        # cookie_dict = {i.split("=")[0]: i.split("=")[-1] for i in cookie.split("; ")}
        # print(cookie_dict)
        cookies={}
        cookies['browerV'] = '3'
        cookies['osV'] = '1'
        cookies['sct'] = '3'
        cookies['sst0'] = '552'
        cookies['SUV'] = '005E5558458CAE4B5B248FD6FBCA10'+str(random.randint(11,99))
        cookies['ABTEST'] = '5|1563947635|v1'
        # cookies['IPLOC'] = 'CN4103'
        # print(cookies)
        return cookies

    #写入文档一行一个
    def writetxt(self,content,txtname):
        try:
            with open(f'{txtname}', 'a+', encoding='utf-8') as f:
                f.write(content + '\n')
        except Exception as e:
            print(e)
            pass

    # 按行读取txt文档的关键词,返回txt列表
    def readtxt(self,txtname):
        wordlist = []
        try:
            for line in open(f'{txtname}', encoding='utf-8'):
                wordlist.append(line.strip())
        except Exception as e:
            print(e)
            pass
        return wordlist
header = {
            # 'User-Agent': UserAgent(verify_ssl=False).random,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Cookie": "ABTEST=2|1561358499|v1; IPLOC=CN1100; SUID=1A4FC17C4631990A000000005D1070A3; SUV=00CDEE0D7CC14F1A5D1070A35DFF7862; SUID=1A4FC17C2113940A000000005D1070A3; weixinIndexVisited=1; pgv_pvi=2997798912; ld=tZllllllll2N9tTHlllllV1S8k7lllllKGV5pklllltlllllpylll5@@@@@@@@@@; LSTMV=682%2C416; LCLKINT=8742; SNUID=F7A22C91EDE961A343DEFB22EDD4F97E; sct=14; JSESSIONID=aaaoA1hhCs7Mf8ji7bsTw",
            "Host": "weixin.sogou.com",
            "Pragma": "no-cache",
            "Referer": "https://weixin.sogou.com/weixin?usip=&query=%E9%98%BF%E5%B0%94%E6%B3%95%E7%8B%97&ft=&tsn=1&et=&interation=&type=2&wxid=&page=2&ie=utf8",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
        }
def get_cookies():
    """
    使用selenium获取cookies的值，将其存在文件中
    :return:
    """
    url = 'https://v.sogou.com/v?ie=utf8&query=&p=40030600'
    headers = {'User-Agent': ua}
    rst = requests.get(url=url, headers=headers, allow_redirects=False)
    cookies = rst.cookies.get_dict()
    print(f"2-[''响应后SNUID'],{rst.cookies.get_dict()['SNUID']}")
    vip= vip_request()
    vip.writetxt(rst.cookies.get_dict()['SNUID'] ,'testlog.txt')
    with open("wx_cookie.json", "w+")as f:
        f.write(json.dumps(cookies))
        f.close()
    print("wx_cookies获取成功")
def get_req():
    """
    打开cookies文件获取cookie，进行requests请求
    :return:
    """
    print("打开cookie文件获取cookies")
    with open("wx_cookie.json", "r")as f:
        cookies = json.loads(f.readline())
    snuid = cookies["SNUID"]
    cookie = "ABTEST=2|1561358499|v1; IPLOC=CN1100; SUID=1A4FC17C4631990A000000005D1070A3; SUV=00CDEE0D7CC14F1A5D1070A35DFF7862; SUID=1A4FC17C2113940A000000005D1070A3; weixinIndexVisited=1; pgv_pvi=2997798912; ld=tZllllllll2N9tTHlllllV1S8k7lllllKGV5pklllltlllllpylll5@@@@@@@@@@; LSTMV=682%2C416; LCLKINT=8742; SNUID={}; sct=14; JSESSIONID=aaaoA1hhCs7Mf8ji7bsTw".format(
        snuid)
    header["Cookie"] = cookie
    header["User-Agent"] = ua
    req = requests.Session()
    req.headers = header
    return req
def cookies_expried():
    """
    判断cookies是否过期，若过期会自动登录获取cookies
    :return:
    """
    file = os.path.isfile("wx_cookie.json")
    if not file:
        get_cookies()
    req = get_req()
    url = "https://weixin.sogou.com/weixin?usip=&query=%E9%98%BF%E5%B0%94%E6%B3%95%E7%8B%97&ft=&tsn=1&et=&interation=&type=2&wxid=&page=3&ie=utf8"
    response = req.get(url, allow_redirects=False)
    print("验证cookies是否可用")
    login_state = True
    if response.status_code == 302:
        login_state = False
    if login_state:
        print("cookies可用")
        return req
    else:
        print("cookies不可用，重新获取cookies")
        get_cookies()
        req = get_req()
        return req

if __name__ == '__main__':
    for i in range(1000):
        time.sleep(2)
        get_cookies()

    # get_req()

